//
//  ZqlStatusListViewModel.swift
//  ZqlSinaWeiBo
//
//  Created by 赵乾龙 on 16/2/26.
//  Copyright © 2016年 Mr.zhao. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD


class ZqlStatusListViewModel: NSObject {
    
    //模型数组
    lazy var statuses = [ZqlStatusModel]()
    
    //加载首页数据
    func loadHomeData(isPullUp:Bool,finished:(isSuccess:Bool) -> () ){
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        guard let token = ZqlAccountVM.shardAccountVM.access_token else{
            
            SVProgressHUD.showErrorWithStatus("请登录")
            
            return
        }
        
        var parameters = ["access_token":token]
        
        //获取最新数据
        var since_id:Int64 = 0
        var max_id:Int64 = 0
        
        if isPullUp{
            max_id = self.statuses.last?.id ?? 0
        }else{
            since_id = self.statuses.first?.id ?? 0
        }
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parameters["max_id"] = "\(max_id-1)"
        }
        
        //发起网络请求
        ZqlHTTPClient.sharedClient.requestJsonDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil{
                finished(isSuccess: false)
                return
            }
            //将字典转换成数组
            guard let array = dict!["statuses"] as? [[String:AnyObject]]
                else{
                    //执行失败的回调
                    finished(isSuccess: false)
                    return
            }
            //实例化数组
            var temArr = [ZqlStatusModel]()
            
            //遍历数组
            for item in array{
                //字典转模型
                let arr = ZqlStatusModel(dict: item)
                //将模型数据添加到数组中
                temArr.append(arr)
            }
            
            //记录数据
            if since_id > 0{
                
                self.statuses = temArr + self.statuses
                
            }else if max_id > 0 {
                
                //存储下拉刷新的数据
                self.statuses += temArr
                
            }else{
                
                self.statuses = temArr
            }
            //执行成功的回调
            finished(isSuccess: true)
        }
        
    }
    
}

    
    

